// pages/movies/more-movie/more-movie.js
var app = getApp() 

var util = require('../../../utils/util.js')

Page({
data: {
  navigateTitle: "",
  movies: {},
  requestUrl: "",
  totalCount: 0,
  isEmpty:true
},

/**
 * 生命周期函数--监听页面加载
 */
onLoad: function (options) {
    var category = options.category
    this.data.navigateTitle = category

    //让小程序顶部根据数据改变
  wx.setNavigationBarTitle({
    title: category,
  })
    var dataUrl = "" 
  switch (category) {
    case "正在热映":
    dataUrl = app.globalData.doubanBase + '/v2/movie/in_theaters'       
    break ;

    case "即将上映": 
    dataUrl = app.globalData.doubanBase + '/v2/movie/coming_soon'
    break ;

    case "豆瓣排行": 
    dataUrl = app.globalData.doubanBase + '/v2/movie/top250'
    break ; 
  }
  util.http(dataUrl, this.processDoubanData)
  this.data.requestUrl = dataUrl
},

  processDoubanData:function(moviesDouban) {
  var movies = []
  for (var idx in moviesDouban.subjects) {
    var subject = moviesDouban.subjects[idx];
    var title = subject.title;
    //如果title文字大于6  将截取为 ...
    if (title.length >= 6) {
      title = title.substring(0, 6) + "...";
    }
    // 5.0[1,1,1,1,1]  3.0[1,1,1,0,0]

    var temp = {
      title: title,
      //综合评分
      average: subject.rating.average,
      //封面海报
      coverageUrl: subject.images.large,
      //ID 为了详情页面跳转
      movieId: subject.id,
      //星星的评分
      stars: util.convertToStarsArray(subject.rating.stars)
    }
    movies.push(temp)
  }
  var totalMovies = {}
this.data.totalCount += 20;
   //如果要绑定新加载的数据，那么需要同旧有的数据合并在一起
  if(!this.data.isEmpty) {
   totalMovies = this.data.movies.concat(movies)
  }
  else {
    totalMovies = movies 
    this.data.isEmpty = false
  }

  this.setData({
    movies: totalMovies
  })
    
    //关闭加载图标
    wx.hideNavigationBarLoading()
    
     //停止下拉刷新动作
    wx.stopPullDownRefresh()


},



  onMovieTap: function (event) {
    var movieId = event.currentTarget.dataset.movieid;
    wx.navigateTo({
      url: '../movie-detail/movie-detail?id=' + movieId
    })
  },
  

  
/**
 * 生命周期函数--监听页面初次渲染完成
 */
onReady: function () {
},

/**
 * 生命周期函数--监听页面显示
 */
onShow: function () {

},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide: function () {

},

/**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {

},

/**
 * 页面相关事件处理函数--监听用户下拉动作
 */
onPullDownRefresh: function (e) {
  var refreshUrl = this.data.requestUrl +
  "?star=0&count=20"
  this.data.movies = {}
  this.data.isEmpty = true
  this.data.totalCount =0
  util.http(refreshUrl, this.processDoubanData);
  //下拉刷新图标
  wx.showNavigationBarLoading()
},

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom: function (e) {
  var nextUrl = this.data.requestUrl + "?start=" + 
  this.data.totalCount + "&count=20"
  util.http(nextUrl, this.processDoubanData)  
  //开启加载图标
  wx.showNavigationBarLoading();
},

/**
 * 用户点击右上角分享
 */
onShareAppMessage: function () {

},

})